package day04;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/4/11
 */
public class DiagonalSum {
    public static void main(String[] args) {
        int[][] array = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        int sum = calculateDiagonalSum(array);
        System.out.println("两条对角线元素之和为: " + sum);
    }

    public static int calculateDiagonalSum(int[][] matrix) {
        int sum = 0;
        int n = matrix.length;

        for (int i = 0; i < n; i++) {
            // 主对角线元素
            sum += matrix[i][i];
            // 副对角线元素(不重复计算中心元素)
            if (i != n - 1 - i) {
                sum += matrix[i][n - 1 - i];
            }
        }

        return sum;
    }
}
